<template>
	<view class="container">
		<!-- <u-navbar :is-back="true" :title="linename" :border-bottom="false" :background="background">
		</u-navbar> -->
		<!-- 导航 -->
		<u-navbar v-if="position=='top'" :is-back="true" :title="lineBascInfo.lineName" :background="background"
			:border-bottom="false">
		</u-navbar>

		<u-navbar v-else title-color="#fff" :is-fixed="true" :is-back="false" :border-bottom="false">
			<view class="slot-wrap">
				<diyNav text=" " :isTwo="false" :isWhite="false" background=""></diyNav>
			</view>
		</u-navbar>

		<!-- 底层地图 -->
		<view class="map-contarin">
			<map id="pathDetailMap" ref="pathDetailMap" class="map-content" :style="{height:mapHeight}"
				:markers="markers" :polyline="polyline" :latitude="latitude" :longitude="longitude"
				@regionchange="bindregionchange" :showLocation="showLocation" :scale="scale">
			</map>
		</view>

		<!-- :style="'top:'+drawerTop+'px;'" -->
		<!-- 滑动层 -->
		<view class="layer" :animation="animationData" :style="'top:'+drawerTop+'px;'" @touchend="onTouchEnd"
			@touchstart="onTouchStart" @touchmove.stop="onTouchMove">

			<!-- 第一段 -->
			<view class="one">
				<!--  定位按钮-->
				<view class="location" @click="onLocation">
					<image class="v-location" src="@/static/images/bus/ico_map_location.png">
					</image>
				</view>

				<view class="top-layer">
					<!-- 方向箭头 -->
					<view class="arrup-main">
						<image v-if="position!='bottom'" src="@/static/images/bus/arrow_down.png" mode=""></image>
						<image v-if="position=='bottom'" src="@/static/images/bus/arrow_up.png" mode=""></image>
					</view>

					<!-- 线路信息 -->
					<view class="line-information-box">
						<view class="start-stop-station">
							<view class="station home-font-main-34">
								<text class="start-station">{{lineBascInfo.startStationName}}</text>
								<image src="/static/images/bus/direction.png"></image>
								<text class="stop-station">{{lineBascInfo.endStationName}}</text>
							</view>
							<view class="reversing-button home-font-main-34" @click="changeDirection"
								v-if="lineBascInfo.drivingDirection != 3">
								<image src="/static/images/bus/ex_dir.png"></image>
								<text>换向</text>
							</view>
						</view>
						<view class="distance-price font-color-weak-28">
							<text class="distance">全程:{{lineBascInfo.totalMileage}}公里</text>
							<text class="price">票价:{{lineBascInfo.ticketPrice}}元</text>
						</view>
						<view class="time font-color-weak-28">
							<text>首{{lineBascInfo.firstTime}} 末{{lineBascInfo.lastTime}}</text>
						</view>
					</view>

					<!-- 实时公交信息 -->
					<view class="card-panel">
						<view class="station-name font-color-weak-28">
							距<text>{{selectStation.stationName}}</text>最近{{effectiveCarList.length > 2 ? 2 : effectiveCarList.length}}班：
						</view>
						<view class="bus-list">

							<!-- <view class="bus-list-item">
								<view class="top">
									<image class="gif-img" src="/static/images/bus/an_realtime.gif"></image>
									<view class="time-box"><text class="time-value">20</text>分钟</view>
								</view>
								<view class="bottm">
									<text class="staion-num">13站·</text>
									<text class="distance">2公里</text>
								</view>
							</view>
							<view class="bus-list-item">
								<view class="single-line-tips">
									已到站
								</view>
							</view> -->

							<block v-for="(busItem,busIndex) in effectiveCarList" :key="busIndex">
								<view class="bus-list-item" v-if="busIndex < 2 && busItem.targetStationDistance >= 30">
									<view class="top">
										<image class="gif-img" src="/static/images/bus/an_realtime.gif"></image>
										<view class="time-box">
											<text class="time-value" v-if="busItem.targetStationTime>0">{{busItem.targetStationTime}}</text>
											<text v-else>小于<text class="time-value">1</text></text>
											
											分钟
										</view>
									</view>
									<view class="bottm">
										<text class="staion-num" v-if="busItem.targetStationDistance > 400">{{busItem.targetStationCount}}站·</text>
										<text class="staion-num" v-else>即将到站·</text>
										<text class="distance">{{busItem.targetStationDistance | distanceFormat}}</text>
									</view>
								</view>
								
								<view class="bus-list-item" v-if="busIndex < 2 && busItem.targetStationDistance < 30">
									<view class="single-line-tips">
										已到站
									</view>
								</view>
							</block>

							<!-- 没有车辆时提示 -->
							<view class="nobus-box" v-show="noBusData">
								<view class="tips-text">
									等待首站发车
								</view>
							</view>

						</view>
					</view>

				</view>

				<!-- 公交图示 -->
				<scroll-view class="bus-station-list" style="width:750rpx" :scroll-x="true"
					:scroll-into-view="scrollLeft" :scroll-with-animation="true">
					<view class="bus-station-list-item" v-for="(item,index) in stationsList" :id="'bus_'+index"
						:key="index">
						<!-- 站点 -->
						<view class="station-info">
							<!-- 车 -->
							<!-- <view class="bus-image-box" v-if="index == 5">
								<text class="bus-num">2辆</text>
								<image class="bus-image" src="/static/images/bus/bus_icon.png"></image>
							</view> -->
							<block v-for="(busItem,busIndex) in carList" :key="busIndex">
								<!-- v-if="busItem.nextNo-1 == item.stationNo && busItem.nextStationDistance<10" -->
								<view class="bus-image-box" v-if="test(item,busItem)">
									<!-- <text class="bus-num">2辆</text> -->
									<!-- <text class="bus-num">{{busItem.busNum}}</text> -->
									<image class="bus-image" src="/static/images/bus/bus_icon.png"></image>
								</view>
							</block>


							<!-- 中间点 -->
							<view class="status-bg">
								<!-- 起点 -->
								<image class="station-image start-image" v-if="index == 0"
									src="/static/images/bus/qi5.png" style="width: 40rpx;height: 40rpx;"></image>
								<!-- 终点 -->
								<image class="station-image stop-image" v-else-if="stationsList.length-1 == index"
									src="/static/images/bus/zhong.png" style="width: 40rpx;height: 40rpx;"></image>
								<!-- 选中 -->
								<image class="station-image right_arrow" v-else-if="index == selectStationIndex"
									src="/static/images/bus/right_arrow.png"></image>
								<!-- 白色箭头 -->
								<image class="station-image white_arrow" v-else
									src="/static/images/bus/white_arrow.png"></image>
							</view>

							<!-- 底部站名 -->
							<view class="station-name" @click="changeStation(index)">
								<view :class="{'select-active' : index == selectStationIndex}">{{item.stationName}}
								</view>
								<view class="tag" v-if="item.stationName == stationName">
									离我最近
								</view>
							</view>
						</view>
						<!-- 中间线 -->
						<view class="line-info" v-if="stationsList.length-1 > index">
							<!-- <view class="bus-image-box" v-if="index == 9">
								<text class="bus-num">2辆</text>
								<image class="bus-image" src="/static/images/bus/bus_icon.png"></image>
							</view> -->

							<block v-for="(busItem,busIndex) in carList" :key="busIndex">
								<view class="bus-image-box" v-if="test1(item,busItem)">
									<!-- <text class="bus-num">2辆</text> -->
									<!-- <text class="bus-num">{{busItem.busNum}}</text> -->
									<image class="bus-image" src="/static/images/bus/bus_icon.png"></image>
								</view>
							</block>

							<view class="line"></view>
						</view>
					</view>
				</scroll-view>

			</view>


		</view>
		

		<view class="footer">
			<view class="wrap-footer">
				<view class="column">
					<button open-type="feedback" style="display: contents;" class="btn-feedback">
						<image src="@/static/images/bus/feedback.png"></image>
						<text>反馈</text>
					</button>
				</view>

				<view @click="refreshHandel" class="column">
					<image src="@/static/images/bus/icon-fresh.png"></image>
					<text>刷新</text>
				</view>
				<!-- <view class="column" style="margin-right:100rpx;margin-top:14rpx">
							<image
								src="@/static/images/bus/btn-save.png"
								style="width:46rpx;height:46rpx"></image>
							<text class="isfavorite?'tab-text-green':'tab-text-gray'"
								style="font-size:22rpx;text-align:center;margin-top:6rpx;">收藏</text>
						</view> -->
				<view class="column" v-if="!isCollect" @click="cancelCollect">
					<image src="@/static/images/bus/unbtn-save.png"></image>
					<text class="unbtn-save">收 藏</text>
				</view>
				<view class="column" v-else="isCollect" @click="removeCollect">
					<image src="@/static/images/bus/btn-save.png"></image>
					<text class="btn-save">已收藏</text>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				source:1,//1公交站下点击线路，2搜索页，3收藏页
				// 头部
				background: {
					background: '#fff'
				},
				// 当前位置经纬度-搜索公交线路页进详情使用
				curLocation: {
					latitude: '',
					longitude: ''
				},

				// 地图
				latitude: 26.635865,
				longitude: 106.646815,
				showLocation: true,
				scale: 14, //地图缩放级别
				mapHeight: '30vh',
				animationData: '', //动画

				drawerTop: 150, //滑动时距离顶部的距离
				viewPageTop: 0, //滑动的div距离顶部的距离

				screenHeight: 0, //设备高
				topLayerHeight: 0, //顶层显示元素高
				centerLayerHeight: 0, //中间位置显示元素高
				footerHeight: 0, //底部操作面板的高
				statusBarHeight: 0, //状态栏高

				position: 'center', //层的位置，center中间，top顶上，bottom底部
				scrollLeft: 'bus_0', //底部选中站点滚动至可视区域

				touchStartX: 0, // 触屏起始点x
				touchStartY: 0, // 触屏起始点y


				lineId: null, //线路id
				segmentId:'',//线路id，单程id
				drivingDirection: 1,//行驶方向 1.上行  2.下行 3.环形
				isCollect: false,//是否收藏
				collectId:'',//收藏id
				
				stationName: '', //站点名
				lineRawData: {}, //线路原始数据
				realBusList: [], //实时原始公交数据

				lineBascInfo: {
					drivingDirection: 1, //行驶方向 1.上行  2.下行 3.环形
					lineName: '', //线路名
					startStationName: '起始站', //起点站
					endStationName: '终点站', //终点站
					firstTime: '6:30', //首班发车时间
					lastTime: '22:00', //末班发车时间
					ticketPrice: '2', //票价
					totalMileage: '9.6' //线路全程距离
				},

				stationsList: [], //站点列表
				selectStation: {}, //选中的站点
				selectStationIndex: 1, //选中的站点索引


				carList: [], //车辆列表
				effectiveCarList: [], //未过目标站点的列表
				noBusData: false,


				markers: [], //所有标注

				stationMarkers: [], //站点标注
				carMarkers: [], //车辆标注
				selectStationMarkers: [], //选中站点标注，只能选中一个

				points: [], //线路点
				polyline: [], //线路

				setInterName: null //定时器对象
			};
		},
		filters: {
			distanceFormat(val) {
				if (val < 1000) {
					return val.toFixed(0) + '米';
				} else {
					let distance = val / 1000;
					return distance.toFixed(1) + '公里';
				}

			}

		},
		watch: {
			selectStationIndex(index) { //站点列表滚动中心
				// console.log(index);
				if (this.selectStationIndex <= 3) {
					this.scrollLeft = 'bus_0';
				} else if (parseInt(this.stationsList.length - 3) <= this.selectStationIndex) {
					this.scrollLeft = 'bus_' + this.selectStationIndex;
				} else {
					this.scrollLeft = 'bus_' + parseInt(this.selectStationIndex - 3);
				}
			}
		},
		components: {
			
			
		},
		onLoad(option) {
			console.log(JSON.stringify(option));
			// var option = {"source":"1","stationId":"003101000000450003001311","stationName":"国际会议中心(东)","lineId":"01000000028003001163"};
			
			this.lineId = option.lineId;
			this.source = option.source;
			if (this.source == 1) {
				this.stationName = decodeURIComponent(option.stationName);
			} else {
				// 搜索/收藏
				if(this.source == 3){
					this.drivingDirection = option.drivingDirection;
				}
				this.curLocation = uni.getStorageSync('getData');
			}
			this.getLineDetails();
		},
		onShow() {
			let that = this;
			// 获取屏幕高度
			uni.getSystemInfo({
				success: function(res) {
					that.screenHeight = res.screenHeight;
					// #ifdef MP-WEIXIN
					that.statusBarHeight = res.statusBarHeight;
					console.log('状态栏高度:' + res.statusBarHeight);
					// #endif
				}
			});
			this.setInterName = setInterval(() => {
				if(that.selectStation.stationId !== undefined 
				&& that.selectStation.stationId !== null){
					that.getRealBus();
				}
			}, 5000)
		},
		onUnload() {
			clearInterval(this.setInterName);
		},
		onHide() {
			clearInterval(this.setInterName);
		},
		methods: {
			onTouchStart: function(e) {
				var that = this;
				this.touchStartX = e.touches[0].clientX;
				this.touchStartY = e.touches[0].clientY;

				const query = uni.createSelectorQuery().in(that);
				query.select('.layer').boundingClientRect(data => {
					// console.log(data)
					that.viewPageTop = e.changedTouches[0].clientY - data.top;
				}).exec();


				// let info = uni.createSelectorQuery().select(".top-layer");
				// info.boundingClientRect(function(data) { //data - 各种参数
				// 	that.topLayerHeight = data.height;
				// 	console.log("高度"+that.topLayerHeight);
				// }).exec()

				let info1 = uni.createSelectorQuery().select(".one");
				info1.boundingClientRect(function(data) { //data - 各种参数
					that.centerLayerHeight = parseInt(data.height);
				}).exec()


				// let info2 = uni.createSelectorQuery().select(".footer");
				// info2.boundingClientRect(function(data) { //data - 各种参数
				// 	that.footerHeight = parseInt(data.height);
				// }).exec()

			},
			onTouchMove: function(e) {
				let ret = e.changedTouches[0].clientY - this.viewPageTop
				if (ret < 0 || ret > 200) { //滑动距离控制
					return;
				}
				this.drawerTop = ret;
			},
			onTouchEnd: function(e) {
				var n = uni.createAnimation({
					duration: 150,
					timingFunction: "ease-in-out"
				});
				// console.log("触摸结束")  
				let deltaX = e.changedTouches[0].clientX - this.touchStartX;
				let deltaY = e.changedTouches[0].clientY - this.touchStartY;
				if (Math.abs(deltaX) > 50 && Math.abs(deltaX) > Math.abs(deltaY)) {} else if (Math.abs(deltaY) > 50 &&
					Math.abs(deltaX) < Math.abs(deltaY)) {
					if (deltaY < 0) {  //上滑
						// console.log(1);
						if (this.position == 'center') {
							n.top(this.statusBarHeight + 44).step();
							this.position = 'top';
						}
						if (this.position == 'bottom') {
							let setCenterPositionHeight = this.screenHeight - this.centerLayerHeight;
							n.top(150).step();
							this.position = 'center';
							// this.scale = 14;
							this.mapHeight = '30vh';
						}

					} else {  // 下滑

						if (this.position == 'center') {
							// let setBottomPositionHeight = this.screenHeight - this.topLayerHeight + this.footerHeight;
							let setBottomPositionHeight = this.screenHeight - 176;
							n.top(setBottomPositionHeight).step();
							this.position = 'bottom';
							// this.scale = 14;
							this.mapHeight = '80vh';
						}

						if (this.position == 'top') {
							let setCenterPositionHeight = this.screenHeight - this.centerLayerHeight;
							n.top(150).step();
							this.position = 'center';
							// this.scale = 14;
							this.mapHeight = '30vh';
						}

					}
					// #ifdef MP-WEIXIN
					// #endif
				} else {
					return false;
				}

				this.animationData = n.export();
			},
			// 设置地图中心点偏移
			setCenterOffset() {
				let map = uni.createMapContext('pathDetailMap');
			},
			onLocation() {
				var that = this;
				// #ifdef MP-WEIXIN
				uni.showLoading({
					title: '定位中...'
				})
				uni.getLocation({
					type: 'gcj02',
					altitude: true,
					success: function(res) {
						uni.hideLoading();
						let getData = {
							"longitude": res.longitude,
							"latitude": res.latitude
						}
						that.curLocation = getData;
						uni.setStorageSync('getData', getData);
					},
					complete: function(res) {
						uni.hideLoading();
					},
					fail: function(res) {}
				});
				let map = uni.createMapContext('pathDetailMap');
				map.moveToLocation({
					latitude: that.curLocation.latitude,
					longitude: that.curLocation.longitude
				})
				// #endif
			},

			/***地图视野发生变化***/
			bindregionchange(e) {
				let map = uni.createMapContext('pathDetailMap');
				var that = this;
				return;
				map.getScale({
					success(res) {
						// console.log(res.scale);
						map.getCenterLocation({
							success: function success(res1) {
								// 移动地图，查询IPO点，
								if (that.scale != res.scale) {
									that.scale = res.scale;
									that.initStationMarkers(that.stationsList);
									return;
								}
							}
						});
					}
				})
			},
			
			getLineDetails() { // 线路信息
				let that = this;
				if(!this.$Common.isGetToken()){
					this.$Common.replaceToken();
				}
				let header = {
					"content-type": "application/json",
					"Authorization": "Bearer " + uni.getStorageSync('token')
				};
				this.$request({
					url: this.$API.getLineDetails,
					data: {
						"lineId": that.lineId
					},
					header: header,
					isShowLoading: true,
					lodingText: '加载中...',
					timeout: 30000
				}).then(res => {
					// console.log(JSON.stringify(res));
					if (res.code == 200) {
						that.lineRawData = res.data;
						if (that.source == 1) {
							// 初次绑定的线路筛选有列表页带过来站点的方向
							let segments = res.data.segments;
							for (let i = 0; i < segments.length; i++) {
								for (let j = 0; j < segments[i].stations.length; j++) {
									if (segments[i].stations[j].stationName == that.stationName) { //查找同名站点，选择默认站点
										that.lineBascInfo.drivingDirection = segments[i].drivingDirection; //方向标识
										that.stationsList = segments[i].stations;
										that.selectStation = segments[i].stations[j];
										that.selectStationIndex = j;

										that.initLineBascInfo();
										return; //查找到就返回
									}
								}
							}

						} else { //搜索线路，无站点信息，循环判断最近站点
							var recentStation = {};
							var segmentsList = res.data.segments;
							var segments = {};
							if (that.source == 3) {
								for(let i=0;i<segmentsList.length;i++){
									if(that.drivingDirection == segmentsList[i].drivingDirection){
										segments = res.data.segments[i];
									}
								}
							}else{
								segments = res.data.segments[0];
							}
							
							// return;
							// 最近站点信息
							that.selectStation = that.calcStations(segments);
							// that.selectStation = segments.stations[0];
							// 地图线路--方向标识
							that.lineBascInfo.drivingDirection = segments.drivingDirection;

							that.initLineBascInfo();
						}
						
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					console.log(JSON.stringify(err));
				});
			},
			getRealBus(isShowLoading) { //获取实时公交信息
				if(isShowLoading !== true){
					isShowLoading = false;
				}
				if(!this.$Common.isGetToken()){
					this.$Common.replaceToken();
				}
				let that = this;
				let header = {
					"content-type": "application/json",
					"Authorization": "Bearer " + uni.getStorageSync('token')
				};
				let query = {
						"lineId": that.lineId,
						"stationId": that.selectStation.stationId
					};
					// console.log(JSON.stringify(query));
					// if(query.stationId.length !== 0){
					// 	return;
					// }
				this.$request({
					url: this.$API.busInfo,
					data: query,
					header: header,
					isShowLoading:isShowLoading
				}).then(res => {
					if (res.code == 200) {
						that.realBusList = res.data;
						this.filterBusData();
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
					// console.log(JSON.stringify(res));
				}).catch(err => {
					console.log(JSON.stringify(err));
				});
			},

			filterBusData() { // 过滤公交车辆实时数据
				let that = this;
				that.carList = [];
				that.effectiveCarList = [];
				that.carMarkers = [];

				this.realBusList.forEach(val => {
					if (that.lineBascInfo.drivingDirection == "3") { //环线
						that.carList.push(val);
						
						
						if (val.targetStationCount >= 0) { //在目标站点前的车辆
						
							// 到站时间计算
							let speed = val.speed.toFixed(0);
							let targetStationDistance = val.targetStationDistance.toFixed(0);
							
							if(speed>0 && targetStationDistance>0){
								let time = targetStationDistance/speed;
								let timeSeconds = time.toFixed(0) / 60;
								val.targetStationTime = timeSeconds.toFixed(0);
							}					
							that.effectiveCarList.push(val)
							
							let calloutContent = ''
							
							if (targetStationDistance < 1000) {
								if (targetStationDistance < 30) {
									calloutContent = '已抵达'+that.selectStation.stationName;
								}else{
									calloutContent = targetStationDistance + '米后抵达'+that.selectStation.stationName;
								}
								
							} else {
								let distance = targetStationDistance / 1000;
								calloutContent = distance.toFixed(1) + '公里后抵达'+that.selectStation.stationName;
							}
							
							that.carMarkers.push({
								busNum: val.busNum,
								latitude: val.busLocation.split(',')[0],
								longitude: val.busLocation.split(',')[1],
								iconPath: '/static/images/bus/bus-1.png',
								width: 28,
								height: 34,
								anchor: {
									x: .5,
									y: .9
								},
								// rotate: val.azimuth,
								callout: {
									content: calloutContent,
									bgColor: "#000000aa",
									fontSize: 14,
									color: "#ffffff",
									borderRadius: 3,
									display: "ALWAYS",
									textAlign: "center",
									padding: 10
								}
							})
						
						}else{
							that.carMarkers.push({
								busNum: val.busNum,
								latitude: val.busLocation.split(',')[0],
								longitude: val.busLocation.split(',')[1],
								iconPath: '/static/images/bus/bus-1.png',
								width: 28,
								height: 34,
								anchor: {
									x: .5,
									y: .9
								}
							})
						}
						

						// that.carMarkers.push({
						// 	busNum: val.busNum,
						// 	latitude: val.busLocation.split(',')[0],
						// 	longitude: val.busLocation.split(',')[1],
						// 	iconPath: '/static/images/bus/bus-1.png',
						// 	width: 28,
						// 	height: 34,
						// 	anchor: {
						// 		x: .5,
						// 		y: .5
						// 	},
						// 	// rotate: val.azimuth,
						// 	callout: {
						// 		content: "目标站" + val.targetStationDistance.toFixed(1),
						// 		bgColor: "#000000aa",
						// 		fontSize: 14,
						// 		color: "#ffffff",
						// 		borderRadius: 3,
						// 		display: "ALWAYS",
						// 		textAlign: "center",
						// 		padding: 10
						// 	}
						// })

						// if (val.targetStationCount >= 0) { //在目标站点前的车辆
							
						// 	// 到站时间计算
						// 	let speed = val.speed.toFixed(0);
						// 	let targetStationDistance = val.targetStationDistance.toFixed(0);
							
						// 	if(speed>0 && targetStationDistance>0){
						// 		let time = targetStationDistance/speed;
						// 		let timeSeconds = time.toFixed(0) / 60;
						// 		val.targetStationTime = timeSeconds.toFixed(0);
						// 	}					
							
						// 	that.effectiveCarList.push(val)
						// }

					} else if (val.drivingDirection == that.lineBascInfo.drivingDirection) { //过滤出同向数据
						that.carList.push(val);


						if (val.targetStationCount >= 0) { //在目标站点前的车辆
						
							// 到站时间计算
							let speed = val.speed.toFixed(0);
							let targetStationDistance = val.targetStationDistance.toFixed(0);
							
							if(speed>0 && targetStationDistance>0){
								let time = targetStationDistance/speed;
								let timeSeconds = time.toFixed(0) / 60;
								val.targetStationTime = timeSeconds.toFixed(0);
							}					
							that.effectiveCarList.push(val)
							
							let calloutContent = ''
							
							if (targetStationDistance < 1000) {
								if (targetStationDistance < 30) {
									calloutContent = '已抵达'+that.selectStation.stationName;
								}else{
									calloutContent = targetStationDistance + '米后抵达'+that.selectStation.stationName;
								}
								
							} else {
								let distance = targetStationDistance / 1000;
								calloutContent = distance.toFixed(1) + '公里后抵达'+that.selectStation.stationName;
							}
							
							that.carMarkers.push({
								busNum: val.busNum,
								latitude: val.busLocation.split(',')[0],
								longitude: val.busLocation.split(',')[1],
								iconPath: '/static/images/bus/bus-1.png',
								width: 28,
								height: 34,
								anchor: {
									x: .5,
									y: .9
								},
								// rotate: val.azimuth,
								callout: {
									content: calloutContent,
									bgColor: "#000000aa",
									fontSize: 14,
									color: "#ffffff",
									borderRadius: 3,
									display: "ALWAYS",
									textAlign: "center",
									padding: 10
								}
							})
						
						}else{
							that.carMarkers.push({
								busNum: val.busNum,
								latitude: val.busLocation.split(',')[0],
								longitude: val.busLocation.split(',')[1],
								iconPath: '/static/images/bus/bus-1.png',
								width: 28,
								height: 34,
								anchor: {
									x: .5,
									y: .9
								}
							})
						}
						
					}
				})

				that.effectiveCarList = that.effectiveCarList.sort(that.compare('targetStationCount'));
				that.effectiveCarList.length == 0 ? that.noBusData = true : that.noBusData = false;
				that.markers = [...that.stationMarkers, ...that.carMarkers]; //...展开运算符
			},
			compare(property) { //公交排序
				return function(a, b) {
					var value1 = a[property];
					var value2 = b[property];
					return value1 - value2;
				}
			},

			initLineBascInfo() { //初始化线路基本信息
				// 当前方向线路
				let that = this;
				let lineArr = this.lineRawData.segments;
				// console.log(lineArr);
				let line = null;
				for (let i = 0; i < lineArr.length; i++) {
					if (lineArr[i].drivingDirection == that.lineBascInfo.drivingDirection) {
						line = lineArr[i]
					}
				}

				// console.log(JSON.stringify(line));
				this.segmentId = line.segmentId;//单程线路id
				this.queryIsCollect();//获取是否收藏
				
				this.lineBascInfo.lineName = this.lineRawData.lineName

				this.lineBascInfo.firstTime = line.firstTime;
				this.lineBascInfo.lastTime = line.lastTime;
				this.lineBascInfo.ticketPrice = line.ticketPrice;

				//线路全程长度米转为公里 
				let totalMileage = line.totalMileage / 1000;
				this.lineBascInfo.totalMileage = totalMileage.toFixed(1);

				this.lineBascInfo.startStationName = line.stations[0].stationName;
				this.lineBascInfo.endStationName = line.stations[line.stations.length - 1].stationName;

				this.stationsList = line.stations;
				
				this.latitude = this.selectStation.latitude;
				this.longitude = this.selectStation.longitude;
				
				 //换向时站点选中
				let selectStationNo = '';
				this.stationsList.forEach((val,index)=>{ 
					if(val.stationName == that.selectStation.stationName){
						that.selectStationIndex = index; 
						selectStationNo = index;
					}
				}) 
				if(selectStationNo == ''){  //找不到同名站时选择离该站点最近的一个选中
					selectStationNo = this.stationsList.length-this.selectStation.stationNo;
					selectStationNo > 0 ? that.selectStationIndex = selectStationNo : that.selectStationIndex = 0;
					// that.selectStationIndex>=0?that.selectStationIndex:2;
				}
				
				this.selectStation = this.stationsList[this.selectStationIndex];
				
				this.initStationMarkers(line.stations);
				this.initPolyLine(JSON.parse(line.segmentTrajectory))
				
				if(that.selectStation.stationId !== undefined
				&& that.selectStation.stationId !== null){
					that.getRealBus();
				}
			},

			initPolyLine(segmentTrajectory) { // 设置公交线路
				let that = this
				that.polyline = []
				that.points = []
				segmentTrajectory.forEach(function(item) {
					that.points.push({
						latitude: item.latitude,
						longitude: item.longitude
					})
				})
				
				let polyline = [{ //指定一系列坐标点，从数组第一项连线至最后一项
					points: this.points,
					color: "#26a2ff", //线的颜色
					width: 9, //线的宽度
					borderColor: "#26a2ff",
					dottedLine: false,
					borderWidth: true,
					arrowLine: true, //带箭头的线 开发者工具暂不支持该属性
				}]
				that.polyline = polyline
			},
			initStationMarkers(stations) { // 处理地图标记点
				var that = this;
				this.stationMarkers = []; //先清空
				stations.forEach((item, index) => {
					// console.log(index);
					let obj = null;
					if (index == 0) { //开始
						obj = {
							id: index,
							latitude: item.latitude,
							longitude: item.longitude,
							iconPath: '/static/images/bus/start_point.png',
							width: 20,
							height: 20,
							anchor: {
								x: .5,
								y: 1
							},
							label: {
								content: item.stationName,
								color: "#1B1B1B",
								fontSize: 12,
								padding: 5,
								textAlign: "center",
								bgColor: "#ffffff",
								borderRadius: 5,
								y: 7,
								x: 3
							}
						}
					} else if (index == stations.length - 1) { //结束
						obj = {
							id: index,
							latitude: item.latitude,
							longitude: item.longitude,
							iconPath: '/static/images/bus/end_point.png',
							width: 20,
							height: 20,
							anchor: {
								x: .5,
								y: 1
							},
							label: {
								content: item.stationName,
								color: "#1B1B1B",
								fontSize: 12,
								padding: 5,
								textAlign: "center",
								bgColor: "#ffffff",
								borderRadius: 5,
								y: 7,
								x: 3
							}
						}
					} else { //中间
						if(that.selectStationIndex == index){
							obj = {
								id: index,
								latitude: item.latitude,
								longitude: item.longitude,
								iconPath: '/static/images/bus/station_car.png',
								width: 35,
								height: 35,
								anchor: {
									x: .5,
									y: .9
								},
								label: {
									content: item.stationName,
									color: "#1B1B1B",
									fontSize: 12,
									padding: 5,
									textAlign: "center",
									bgColor: "#ffffff",
									borderRadius: 5,
									y: 7,
									x: 3
								}
							}
						}else{
							obj = {
								id: index,
								latitude: item.latitude,
								longitude: item.longitude,
								iconPath: '/static/images/bus/bus-staion-bule.png',
								width: 15,
								height: 15,
								anchor: {
									x: .5,
									y: .5
								},
								label: this.scale >= 15 ? {
									content: item.stationName,
									color: "#1B1B1B",
									fontSize: 12,
									padding: 5,
									textAlign: "center",
									bgColor: "#ffffff",
									borderRadius: 5,
									y: 7,
									x: 3
								} : ''
							}
						}
						
					}
					this.stationMarkers.push(obj);
				})
				this.markers = this.stationMarkers;
			},
			// 切换站点
			changeStation(index) { //切换站点
				// console.log(JSON.stringify(this.stations[index]));
				this.selectStationIndex = index;
				this.selectStation = this.stationsList[index];
				this.latitude = this.selectStation.latitude;
				this.longitude = this.selectStation.longitude;
				// 刷新站点信息
				this.initStationMarkers(this.stationsList);
				this.getRealBus();
			},
			//换向
			changeDirection() { 

				if (this.lineBascInfo.drivingDirection == "1") {
					this.lineBascInfo.drivingDirection = "2";
					this.initLineBascInfo();
					return true;
				}

				if (this.lineBascInfo.drivingDirection == "2") {
					this.lineBascInfo.drivingDirection = "1";
					this.initLineBascInfo();
					return true;
				}

			},

			// 计算距离当前位置最近的站点
			calcStations(segments) {
				var that = this;
				var stationList1 = segments.stations;
				var recentStation = segments.stations[0];
				/** 获取最近站点 distance计算当前位置距离第一个站点距离，遍历计算每个站点距离当前位置距离 如果比distance小则替换 冒泡算法 **/
				that.stationsList = stationList1;
				var distance = that.calculateDistance(that.curLocation, recentStation);
				for (var i = 0; i < stationList1.length; i++) {
					/** 计算每个站点距离当前位置的距离 **/
					var preStation = stationList1[i];
					var itemDistance = that.calculateDistance(that.curLocation, preStation);
					if (itemDistance < distance) {
						distance = itemDistance;
						recentStation = preStation;
						that.stationId = recentStation['stationId'];
						that.stationName = recentStation['stationName'];
						that.selectStationIndex = i; //选中站点默认等于离我最近的站点
					}
				}
				return recentStation;
			},
			// 计算最近的站点距离当前坐标距离
			calculateDistance(curLocation, preStation) {
				var a = curLocation.longitude,
					r = curLocation.latitude,
					n = preStation.longitude,
					s = preStation.latitude;
				a *= .01745329251994329, r *= .01745329251994329, n *= .01745329251994329, s *= .01745329251994329;
				var i = Math.sin(a),
					u = Math.sin(r),
					o = Math.cos(a),
					c = Math.cos(r),
					l = Math.sin(n),
					f = Math.sin(s),
					h = Math.cos(n),
					m = Math.cos(s),
					v = [],
					p = [];
				v[0] = c * o, v[1] = c * i, v[2] = u, p[0] = m * h, p[1] = m * l, p[2] = f;
				var d = Math.sqrt((v[0] - p[0]) * (v[0] - p[0]) + (v[1] - p[1]) * (v[1] - p[1]) + (v[2] - p[2]) * (v[
						2] - p[2])),
					g = 12742001.5798544 * Math.asin(d / 2);
				return parseFloat(g.toFixed(3));
			},
			test(item, busItem) {
				if (busItem.nextNo - busItem.lastNo == 2 && item.stationNo == busItem.nextNo - 1) {
					// console.log(JSON.stringify(item));
					return true;
				}
				return false;
			
			},
			test1(item, busItem) {
				if (busItem.nextNo - busItem.lastNo == 1 && item.stationNo == busItem.nextNo - 1) {
					// console.log(JSON.stringify(item));
					return true;
				}
				return false;
			
			},
			// 刷新
			refreshHandel(){
				if(this.stationsList.length !== 0){
					this.getRealBus(true);
				}else{
					this.getLineDetails();
				}
			},
			// 获取是否已收藏当前线路
			queryIsCollect(){
				let that = this;
				if(!this.$Common.isGetToken()){
					this.$Common.replaceToken();
				}
				let header = {
					"content-type": "application/json",
					"Authorization": "Bearer " + uni.getStorageSync('token')
				};
				let query = {
						openId:uni.getStorageSync('openId'),
						segmentId:that.segmentId
					};
				this.$request({
					url: this.$API.queryIsCollect,
					data: query,
					header: header,
					isShowLoading: true
				}).then(res => {
					// console.log(JSON.stringify(res));
					if (res.code == 200) {
						if(res.msg == '未收藏'){
							that.isCollect = false;
						}else{
							that.isCollect = true;
							that.collectId = res.data.collectId;
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					console.log(JSON.stringify(err));
				});
			},
			// 收藏
			cancelCollect(){
				let that = this;
				if(!this.$Common.isGetToken()){
					this.$Common.replaceToken();
				}
				let header = {
					"content-type": "application/json",
					"Authorization": "Bearer " + uni.getStorageSync('token')
				};
				let query = {
						openId:uni.getStorageSync('openId'),
						segmentId:that.segmentId
					};
				this.$request({
					url: this.$API.addCollect,
					data: query,
					header: header,
					method: 'POST',
					isShowLoading: true
				}).then(res => {
					// console.log(JSON.stringify(res));
					if (res.code == 200) {
						that.isCollect = true;
						that.collectId = res.data.collectId;
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					console.log(JSON.stringify(err));
				});
			},
			// 取消收藏
			removeCollect(){
				if(!this.$Common.isGetToken()){
					this.$Common.replaceToken();
				}
				let that = this;
				let header = {
					"content-type": "application/json",
					"Authorization": "Bearer " + uni.getStorageSync('token')
				};
				let query = {
						lineCollect:that.collectId
					};
				this.$request({
					url: this.$API.removeCollect,
					data: query,
					header: header,
					method: "DELETE",
					isShowLoading: true
				}).then(res => {
					// console.log(JSON.stringify(res));
					if (res.code == 200) {
						that.isCollect = false;
						that.collectId = '';
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					console.log(JSON.stringify(err));
				});
			}
		}
	}
</script>

<style lang="scss">
	.container {
		background: #fff;
		width: 100vh;
		height: 100vh;
		// color: #888;

		.map-contarin {
			top: 0;
			width: 750rpx;
			height: 100vh;
			position: absolute;

			.map-content {
				width: 750rpx;
				position: relative;
				// height: 100vh;
				// min-height: 240rpx;
				// min-height: 90vh;
			}
		}
	}


	.layer {
		// display: none;
		position: fixed;
		left: 0;
		top: 0;
		z-index: 88;
		width: 100%;
		// height: 100%;
		// overflow: hidden;
		// border: 1px solid red;
		// min-height: 500rpx;
		background-color: #FFFFFF;
		// transform: translateY(350px);
		box-shadow: 0 -10rpx 20rpx 0 rgba(0, 0, 0, .09);
		border-radius: 20rpx 20rpx 0 0;

	}

	.one {
		position: relative;
		// border: 1px solid red;
		// 定位
		.location {
			position: absolute;
			top: -44px;
			right: 10px;

			// border: 1px solid green;
			.v-location {
				width: 70rpx;
				height: 70rpx;
				// margin-right: 30rpx;
				// margin-bottom: 24rpx;
			}
		}

		.top-layer {
			margin: 0 40rpx;

			// 方向箭头
			.arrup-main {
				text-align: center;

				image {
					width: 24px;
					height: 6px;
				}
			}
		}

		// 线路信息
		.line-information-box {
			background: #fff;
			// padding-bottom: 16rpx;
			// border: 1px solid black;
			.start-stop-station {
				display: flex;
				justify-content: space-between;
				margin: 20rpx 0 6rpx;

				.station {
					display: flex;
					align-items: center;

					image {
						width: 30rpx;
						height: 12rpx;
						margin: 0 12rpx;
					}
				}

				.reversing-button {
					image {
						width: 28rpx;
						height: 24rpx;
						margin-top: auto;
						margin-bottom: auto;
					}

					text {
						margin-left: 12rpx;
						white-space: nowrap;
					}
				}
			}

			.distance-price {
				margin-bottom: 4rpx;

				.distance {
					margin-right: 20rpx;
				}
			}
		}

		// 实时公交信息
		.card-panel {
			// border: 1px solid black;
			background-color: #fff;
			border-radius: 16rpx;
			box-shadow: 0rpx 4rpx 16rpx rgba(0, 0, 0, 0.1);
			margin: 60rpx 0 60rpx;
			padding: 30rpx;

			.station-name {
				padding-bottom: 30rpx;

				text {
					color: #000000;
					font-size: 30rpx;
					padding: 0 6rpx;
				}
			}

			.bus-list {
				display: flex;

				.bus-list-item {
					width: 50%;
					padding-left: 40rpx;

					.top {
						display: flex;

						.gif-img {
							width: 12rpx;
							height: 24rpx;
							margin-right: 14rpx;
						}

						.time-box {
							color: #26A2FF;

							.time-value {
								font-weight: 700;
								font-size: 48rpx;
							}
						}
					}

					.bottom {}
					
					// 单行提示
					.single-line-tips{
						color: #26A2FF;
						// font-weight: 700;
						font-size: 40rpx;
						height: 100%;
						display: flex;
						align-items: center;
					}

				}

				.nobus-box {
					// background-color: red;
					// display: block;
					width: 100%;
					padding: 26rpx 0;

					.tips-text {
						// text-align: center;
						color: #26A2FF;
						font-size: 36rpx;
					}
				}
			}
		}


	}

	// 公交图示
	.bus-station-list {
		margin-top: 20rpx;
		white-space: nowrap;

		.bus-station-list-item {
			display: inline-flex;
			width: 130rpx;
			padding-top: 76rpx;
			position: relative;

			&:first-child {
				margin-left: 50rpx;
			}

			.station-info {
				display: flex;
				flex-direction: column;
				align-items: center;

				.status-bg {
					width: 40rpx;
					height: 16rpx;
					background: #26A2FF;
					position: relative;

					// border: 1px solid red;
					.station-image {
						position: absolute;
					}

					// 白色箭头
					.white_arrow {
						top: 0;
						left: 10rpx;
						width: 14rpx;
						height: 14rpx;
						// border: 1px solid red;
					}

					// 当前站点
					.right_arrow {
						top: -6rpx;
						left: 2rpx;
						width: 30rpx;
						height: 30rpx;
						// border: 1px solid red;
					}

					.start-image {
						top: -14rpx;
						left: -2rpx;
						// left: 10rpx;
						width: 40rpx;
						height: 40rpx;
					}

					.stop-image {
						top: -14rpx;
						left: -2rpx;
						width: 40rpx;
						height: 40rpx;
					}

				}

				.station-name {
					position: relative;
					margin-top: 24rpx;
					writing-mode: vertical-lr;
					color: #848484;

					.select-active {
						//选中站点绑定该类
						color: #000000;
					}

					.tag {
						position: absolute;
						color: #26A2FF;
						font-size: 22rpx;
						border: 1rpx solid #26A2FF;
						border-radius: 4rpx;
						padding: 4rpx 2rpx;
						background: rgba(33, 77, 255, 0.06);
					}
				}
			}

			.line-info {
				.bus-image-box {
					margin-left: 46rpx;
				}

				.line {
					width: 100rpx;
					height: 16rpx;
					background: #26A2FF;
					// z-index:1;
					// position: absolute;
					// top: 36rpx;
				}
			}

			.bus-image-box {
				position: absolute;
				top: 0rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				// border: 1px solid red;
				height: 70rpx;

				.bus-num {
					// margin:0rpx auto;
					color: #26A2FF;
					font-size: 12px;
					position: absolute;
					top: 0rpx;
				}

				.bus-image {
					position: absolute;
					top: 36rpx;
					width: 50rpx;
					height: 26rpx;
				}
			}

		}

	}


	.footer {
		// display: none;
		width: 100%;
		position: fixed;
		left: 0rpx;
		right: 0rpx;
		bottom: 0rpx;
		z-index: 1000;

		.wrap-footer {
			display: flex;
			height: 140rpx;
			background: #fefefe;
			box-shadow: inset 0 1px 0 0 rgba(211, 211, 216, .5);
			justify-content: space-around;
			align-items: center;

			.column {
				text-align: center;

				image {
					width: 46rpx;
					height: 46rpx;
					margin: 0 auto;
				}

				text {
					font-size: 22rpx;
					margin-top: 6rpx;
					color: #959595;
				}
				.btn-save{
					color: $uni-color-primary;
				}
				.unbtn-save{
					color: #959595;
				}
			}

			.btn-feedback {
				display: flex;
				flex-direction: column;
			}
		}
	}
</style>
